using System.Collections;
using UnityEngine;

public class SpawnManager : MonoBehaviour
{
    [SerializeField] private GameObject shieldPowerUp;
    [SerializeField] private GameObject asteroid;
    [SerializeField] private GameObject lifePowerUp;
    [SerializeField] private GameManager gameManager;

    private float spawnRangeX = 10f;
    private float spawnRangeY = 5f;
    private int waveNumber = 1;
    
    void Start()
    {
        InvokeRepeating(nameof(SpawnShieldPowerUp),5f,5f);
        InvokeRepeating(nameof(SpawnLifePowerUp),10f,10f);
        SpawnAsteroid(waveNumber);
    }
    
    void Update()
    {
        int asteroidCount = FindObjectsOfType<AsteroidController>().Length;
        if (asteroidCount == 0)
        {
            waveNumber++;
            SpawnAsteroid(waveNumber);
        }
        
    }

    private void SpawnShieldPowerUp()
    {
        Instantiate(shieldPowerUp, SpawnPosition(), shieldPowerUp.transform.rotation);
    }
    
    private void SpawnLifePowerUp()
    {
        Instantiate(lifePowerUp, SpawnPosition(), lifePowerUp.transform.rotation);
    }

    private void SpawnAsteroid(int asteroidToSpawn)
    {
        for (int i = 0; i < asteroidToSpawn; i++)
        {
            Instantiate(asteroid, SpawnPosition(), asteroid.transform.rotation);
        }
    }

    private Vector3 SpawnPosition()
    {
        float spawnPosX = Random.Range(-spawnRangeX, spawnRangeX);
        float spawnPosY = Random.Range(-spawnRangeY, spawnRangeY);
        Vector3 randomPos = new Vector3(spawnPosX, spawnPosY, 0);

        //防止玩家和PowerUp重叠
        Collider[] hitColliders = Physics.OverlapSphere(randomPos, 3.0f);
        if (hitColliders != null)
        {
            foreach (Collider hit in hitColliders)
            {
                if (hit.CompareTag("Player"))
                {
                    SpawnPosition();
                }
            }
        }
        
        return randomPos;
    }
}
